package com.xw.controller.manage;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.xw.common.Const;
import com.xw.model.DicGroupLimit;
import com.xw.model.DicLimit;
import com.xw.service.sysconfig.DicGroupLimitService;
import com.xw.service.sysconfig.DicLimitService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author wangxiaoxiao
 */
@Controller
@RequestMapping("/manage/limit")
@Scope("prototype")
public class LimitController {
    Map<String,Object> map=null;

    @Resource
    private DicLimitService limitService;
    @Resource
    private DicGroupLimitService groupLimitService;


    @RequestMapping(value = "/goAdd")
    public String goAdd(HttpServletRequest request){
        //查询所有一级目录
        List<DicLimit> list=limitService.findFirstLevel();
        request.setAttribute("list",list);
        return "limit/add";
    }

    @RequestMapping(value = "/goEdit")
    public String goEdit(HttpServletRequest request,String id){
        /* 查询一级分类
        *   根据id查询的对象*/
        DicLimit model = new DicLimit();
        model.setLimitPid("0");
        List<DicLimit> list = limitService.queryListByWhere(model);
        DicLimit limit = limitService.queryByUUID(id);
        request.setAttribute("list",list);
        request.setAttribute("model",limit);
        return "limit/edit";
    }

    /**
     * 跳转到菜单权限配置
     * @param request
     * @param glId
     * @return
     */
    @RequestMapping(value = "/findLimit",method = RequestMethod.GET)
    public String findLimit(HttpServletRequest request, String glId){
        map = new HashMap<>(16);
        DicLimit model = new DicLimit();
        List<DicLimit> list = limitService.findByWhere(model);
        List<DicLimit> limitList = Lists.newArrayList();
        Multimap<String,DicLimit> multimap = ArrayListMultimap.create();

        for (DicLimit dicLimit:list){
            multimap.put(dicLimit.getLimitPid(),dicLimit);
            if (Const.PID_ZERO.equals(dicLimit.getLimitPid())){
                limitList.add(dicLimit);
            }
        }
        comparator(limitList);

        for (DicLimit dicLimit:limitList){
            List<DicLimit> dicLimits = (List<DicLimit>) multimap.get(dicLimit.getLimitId());
            //对子级进行从小到大排序
           comparator(dicLimits);
            dicLimit.getList().addAll(dicLimits);
        }
        //获取权限的增删改查操作
        DicGroupLimit groupLimit = groupLimitService.queryByUUID(glId);

        request.setAttribute("model",groupLimit);
        request.setAttribute("limitList",limitList);
        return "limit/list";
    }

    public void comparator(List<DicLimit> limitList){
        //相对一级的进行从小到大排序
        Collections.sort(limitList, new Comparator<DicLimit>() {
            @Override
            public int compare(DicLimit o1, DicLimit o2) {
                return o1.getSortId()-o2.getSortId();
            }
        });
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Object add(HttpServletRequest request,DicLimit model){
        map = new HashMap<>();
        //1.顶级 2.不是顶级
        String top = request.getParameter("top");

        //判断是否在当前类目下存在相同的名称
        DicLimit limit = new DicLimit();
        if ("1".equals(top)){
            limit.setLimitPid("0");
        }else{
            limit.setLimitPid(model.getLimitPid());
        }
        limit.setLimitName(model.getLimitName());
        Integer num = limitService.queryCount(limit);
        if (num>0){
            map.put("code",101);
            map.put("msg","The menu name already exists under the current class");
//            map.put("msg","菜单名称在当前类目下已存在");
            return JSONObject.toJSON(map);
        }

        Integer integer = limitService.saveSelect(model);
        if (integer>0){
            map.put("code",200);
            map.put("msg",Const.OPREATE_MSG_SUCCESS);
        }else{
            map.put("code",101);
            map.put("msg",Const.OPREATE_MSG_ERROR);
        }
        return map;
    }

    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Object edit(HttpServletRequest request,DicLimit model){
        map = new HashMap<>(16);
        /*根据id查询数据库的对象*/
        DicLimit limit = limitService.queryByUUID(model.getLimitId());
        Integer integer =0;
        /*当前菜单名称没变直接保存 */
        if (limit.getLimitName().equals(model.getLimitName())){
            integer = limitService.updateSelective(model);
        }else{
            /*否则就要查询菜单名称在当前一级菜单下是否存在*/
            DicLimit limit1 = new DicLimit();
            limit1.setLimitPid(model.getLimitPid());
            limit1.setLimitName(model.getLimitName());
            Integer integer1 = limitService.queryCount(limit1);
            if (integer1>0){
                map.put("code",101);
                map.put("msg","The menu name already exists under the current class");
//                map.put("msg","菜单名称在当前类目下已存在");
                return map;
            }else{
                integer = limitService.updateSelective(model);
            }
        }

        if (integer>0){
            map.put("code",200);
            map.put("msg",Const.OPREATE_MSG_SUCCESS);
        }else{
            map.put("code",101);
            map.put("msg",Const.OPREATE_MSG_ERROR);
        }
        return map;
    }

    /**
     * 权限资源删除
     * 1.判断是否是顶级 2.是顶级就要把下面的权限也一起删除了
     * @param request
     * @param id
     * @return
     */
    @RequestMapping(value = "/del",method = RequestMethod.POST)
    @ResponseBody
    public Object del(HttpServletRequest request,String id){
        map = new HashMap<>(16);
        map=limitService.del(id);
        return map;
    }



    /**
     * 备用
     * 跳转页面到数据列表页
     * @param request
     * @return
     */
    @RequestMapping(value = "/findAll")
    public String findAll(HttpServletRequest request, String glId){
        DicGroupLimit model = groupLimitService.queryByUUID(glId);
        request.setAttribute("model",model);
        return "limit/list";
    }

    /**
     * 备用
     * @param request
     * @param glId
     * @return
     */
    @RequestMapping(value = "/findAllJson",method = RequestMethod.GET)
    @ResponseBody
    public Object findAllJson(HttpServletRequest request, String glId,Integer page,Integer limit){
        map = new HashMap<>();

        String limitName = request.getParameter("limitName");

        DicLimit model = new DicLimit();
        model.setLimitName(limitName);
        //总条数
        Integer count = limitService.findByWhere(model).size();

        if (page != null && limit != null) {
            PageHelper.startPage(page,limit,false);
        }
        List<DicLimit> list = limitService.findByWhere(model);

        List<DicLimit> limitList = Lists.newArrayList();
        Multimap<String,DicLimit> multimap = ArrayListMultimap.create();


        for (DicLimit dicLimit:list){
            multimap.put(dicLimit.getLimitPid(),dicLimit);
            if (Const.PID_ZERO.equals(dicLimit.getLimitPid())){
                limitList.add(dicLimit);
            }
        }
        //相对一级的进行从小到大排序
        Collections.sort(limitList, new Comparator<DicLimit>() {
            @Override
            public int compare(DicLimit o1, DicLimit o2) {
                return o1.getSortId()-o2.getSortId();
            }
        });

        for (DicLimit dicLimit:limitList){
            List<DicLimit> dicLimits = (List<DicLimit>) multimap.get(dicLimit.getLimitId());
            //对子级进行从小到大排序
            Collections.sort(dicLimits, new Comparator<DicLimit>() {
                @Override
                public int compare(DicLimit o1, DicLimit o2) {
                    return o1.getSortId()-o2.getSortId();
                }
            });
            dicLimit.getList().addAll(dicLimits);
        }

        map.put("code",0);
        map.put("msg","");
        map.put("data",list);
        map.put("count",count);
        map.put("limitList",limitList);
        return map;
    }

}
